package gui;

import javax.swing.AbstractListModel;
import javax.swing.ListModel;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;

import events.listenerWrappers.WeakListDataListenerWrapper;

public class ComboBoxModel<E> extends AbstractListModel<E> implements javax.swing.ComboBoxModel<E>, ListDataListener {
	private static final long serialVersionUID = -6704495152514941177L;
	ListModel<E> wrapped;
	Object selectedObject = null;

	public ComboBoxModel(ListModel<E> content) {
		super();
		wrapped = content;
		WeakListDataListenerWrapper.addWeakListDataListener(wrapped, this);
	}

	@Override
	public int getSize() {
		return wrapped.getSize();
	}

	@Override
	public E getElementAt(int index) {
		return wrapped.getElementAt(index);
	}

	@Override
	public void setSelectedItem(Object anItem) {
		if ((selectedObject != null && !selectedObject.equals( anItem )) ||
				selectedObject == null && anItem != null) {
			selectedObject = anItem;
			fireContentsChanged(this, -1, -1);
		}
	}

	@Override
	public Object getSelectedItem() {
		return selectedObject;
	}

	@Override
	public void intervalAdded(ListDataEvent e) {
		fireIntervalAdded(this, e.getIndex0(), e.getIndex1());
	}

	@Override
	public void intervalRemoved(ListDataEvent e) {
		fireIntervalRemoved(this, e.getIndex0(), e.getIndex1());
	}

	@Override
	public void contentsChanged(ListDataEvent e) {
		fireContentsChanged(this, e.getIndex0(), e.getIndex1());
	}

}
